import router from '@/router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
export const BASE_URL = '/job-api' // 开发环境
// export const BASE_URL = 'https://xrjk.zjqsxxgbyy.com' // 生产环境
export const BASE_UPLOADURL = BASE_URL + '/police/oss/uploadFile' // 上传图片
//创建axios实例
const service = axios.create({
  baseURL: BASE_URL,
  timeout: 5000000, //超时时间
  headers: {
    //编译语言
    'Content-type': 'application/json;charset=utf-8'
  }
})
//请求拦截
service.interceptors.request.use(
  (config) => {
    //请求的数据
    let token = ''
    if (sessionStorage.getItem('xunfei_token')) {
      token = 'Bearer ' + sessionStorage.getItem('xunfei_token')
    }
    const configInfo: any = {
      ...config.headers,
      Authorization: token || ''
    }
    config.headers = configInfo
    return config //必须返回出去，不然请求发不出去
  },
  (error) => {
    //处理错误请求
    return Promise.reject(error)
  }
)
//响应拦截：后端返回来的结果
service.interceptors.response.use(
  (res) => {
    const data: any = res.data
    if (data.code === 200) {
      //请求成功
      return Promise.resolve(data)
    } else {
      ElMessage({
        message: res.data.msg || '系统异常',
        type: 'error'
      })
      if (data.code === 401) {
        router.push('/login')
      }

      return Promise.reject(res)
    }
  },
  (err) => {
    console.log(err, '错误信息的处理') //错误信息的处理
    //处理错误响应
    return Promise.reject(err)
  }
)
//因为别的地方要用，所以就把实例暴露出去，导出
const serviceApi = (e: {
  url: string
  method: 'get' | 'post' | 'put'
  data?: any
  headers?: any
}) => {
  if (e.method === 'get') {
    const config: any = {
      method: 'get',
      url: e.url,
      headers: e.headers
    }
    if (e.data) config.params = e.data
    return service(config)
  }
  if (e.method === 'post') {
    const config: any = {
      method: 'post',
      url: e.url,
      headers: e.headers
    }
    if (e.data) config.data = e.data
    return service(config)
  }
  if (e.method === 'put') {
    const config: any = {
      method: 'put',
      url: e.url,
      headers: e.headers
    }
    if (e.data) config.data = e.data
    return service(config)
  }
}

export default serviceApi
